package com.qingzhuge.member.interceptor;

import com.google.common.collect.Maps;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.common.utils.WebUtil;
import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.member.dto.CheckAuthorizationRequest;
import com.qingzhuge.member.dto.CheckAuthorizationResponse;
import com.qingzhuge.member.service.ISysMemberService;
import com.qingzhuge.web.interceptor.BaseAuthorizationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

import static com.qingzhuge.common.Constants.CURRENT_USER_ID;

/**
 * @author : zero.xiao
 * @description : 权限(Token)验证
 * @date :2018/9/25 0025 下午 12:06
 * @modified :
 * @since : 1.0.0
 */
@Slf4j
public class AuthorizationTokenIntercepter extends BaseAuthorizationInterceptor {

    @Resource
    private ISysMemberService memberService;

    @Override
    public boolean getToken(String token, HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (StringUtils.isEmpty(token)) {
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("code", HttpCode.TOKEN_VALIDATOR_FAILED.value());
            map.put("message", HttpCode.TOKEN_VALIDATOR_FAILED.message());
            WebUtil.writer(response, map);
            return false;
        }
        CheckAuthorizationRequest checkAuthRequest = new CheckAuthorizationRequest();
        checkAuthRequest.setToken(token);
        CheckAuthorizationResponse checkAuthResponse = memberService.validToken(checkAuthRequest);
        if (HttpCode.OK.value().equals(checkAuthResponse.getResCode())) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Object bean = handlerMethod.getBean();
            if (bean instanceof AbstractController) {
//                AbstractController baseController = (AbstractController) bean;
                AbstractController.setUid(checkAuthResponse.getUid());
                AbstractController.setOpenId(checkAuthResponse.getOpenId());
                log.debug("设置用户数据到Controller:Uid:{},OpenId:{}",
                        checkAuthResponse.getUid(),
                        checkAuthResponse.getOpenId());
            }
            //设置userId到request里，后续根据userId，获取用户信息
            request.setAttribute(CURRENT_USER_ID, checkAuthResponse.getUid());
            return true;
        }
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("code", checkAuthResponse.getResCode());
        map.put("message", checkAuthResponse.getResMessage());
        WebUtil.writer(response, map);
        return false;
    }
}
